package com.example.Service;

import com.example.utils.VivoAuth;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.UUID;

import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.util.concurrent.Executors;

/**
 * 调用蓝心大模型的接口
 * ai聊天的主要方法
 */
@Service
public class AiService {

    // TODO: 2025/3/20 流式响应，前端暂时无法正确接收流式数据，目前前端只能接收完流式数据在模拟打印出来
    public SseEmitter vivogptStream(String user, String prompt) throws Exception {
        SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
        
        emitter.onCompletion(() -> System.out.println("SSE 连接完成"));
        emitter.onTimeout(() -> {
            System.out.println("SSE 连接超时");
            emitter.complete();
        });
        emitter.onError((ex) -> {
            System.out.println("SSE 连接错误: " + ex.getMessage());
            emitter.complete();
        });

        Executors.newSingleThreadExecutor().submit(() -> {
            try {
                String appId = "2025985389";
                String appKey = "eAkRKtYXOawsmtVv";
                String URI = "/vivogpt/completions/stream";
                String DOMAIN = "api-ai.vivo.com.cn";
                String METHOD = "POST";
                UUID requestId = UUID.randomUUID();

                Map<String, Object> queryParams = new HashMap<>();
                queryParams.put("requestId", requestId.toString());
                String queryStr = mapToQueryString(queryParams);

                Map<String, String> data = new HashMap<>();
                data.put("prompt", user + prompt);
                data.put("model", "vivo-BlueLM-TB-Pro");
                data.put("sessionId", UUID.randomUUID().toString());

                HttpHeaders headers = VivoAuth.generateAuthHeaders(appId, appKey, METHOD, URI, queryStr);
                headers.setContentType(MediaType.APPLICATION_JSON);

                String url = String.format("https://%s%s?%s", DOMAIN, URI, queryStr);

                RestTemplate restTemplate = new RestTemplate();
                restTemplate.execute(url, HttpMethod.POST, request -> {
                    request.getHeaders().addAll(headers);
                    request.getBody().write(new ObjectMapper().writeValueAsString(data).getBytes());
                }, response -> {
                    try (InputStream inputStream = response.getBody();
                         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

                        StringBuilder buffer = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.startsWith("data:")) {
                                String jsonData = line.substring(5).trim();
                                System.out.println("AI Response: " + jsonData);

                                // 处理错误消息
                                if (jsonData.contains("使用的人太多啦，请稍后再试~")) {
                                    emitter.send(SseEmitter.event().data("错误：服务器繁忙，请稍后再试"));
                                    emitter.complete();
                                    break;
                                }

                                // 将数据添加到缓冲区
                                buffer.append(jsonData);

                                // 实时发送缓冲区中的数据
                                emitter.send(SseEmitter.event().data(buffer.toString()));

                                // 清空缓冲区
                                buffer.setLength(0);

                                if (jsonData.equals("[DONE]")) {
                                    emitter.complete();
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        emitter.completeWithError(e);
                    }
                    return null;
                });
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }

public static String mapToQueryString(Map<String, Object> map) {
        if (map.isEmpty()) {
            return "";
        }
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (queryStringBuilder.length() > 0) {
                queryStringBuilder.append("&");
            }
            queryStringBuilder.append(entry.getKey());
            queryStringBuilder.append("=");
            queryStringBuilder.append(entry.getValue());
        }
        return queryStringBuilder.toString();
    }
}

